<template>

    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i>订单结账
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container" :style="isPc ?'padding:30px': 'padding:10px'">


          <el-row :gutter="0" >
            <el-col :xs="24" :md="8" style="margin-bottom: 5px">
              <el-button type="primary" icon="el-icon-plus" style="margin-right: 5px" @click="addUserVisible = true">新增会员</el-button>
              <el-autocomplete
                  style="width: 50%"
                  v-model="qryStr"
                  :debounce=0
                  ref="selectUser"
                  :fetch-suggestions="queryUserName"
                  @select="confirmSelect"
                  @clear="clearSelect"
                  class="add-dialog-input mr10"
                  placeholder="选择会员"
                  prefix-icon="el-icon-user"
                  clearable>
              </el-autocomplete>
              <span style="font-size: 13px;margin: 0 5px">余额:{{userMoney}}</span>
            </el-col>

            <el-col :xs="24" :md="8" style="margin-bottom: 5px">
              <el-autocomplete
                  v-model="bar_code"
                  style="width: 70%"
                  v-focus
                  id="bar-code-input"
                  :fetch-suggestions="querySearchSkus"
                  placeholder="请搜索选择商品条形码/商品名"
                  prefix-icon="el-icon-shopping-cart-full"
                  @select="handleSelect"
              ></el-autocomplete>
              <el-button type="success" style="margin-left: 10px;min-width: 60px" @click="openDialog">结 账</el-button>
            </el-col>
          </el-row>
            <el-table
                    :data="computedTableData"
                    border
                    class="table"
                    show-summary
                    :summary-method="getSummaries"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
            >
                <el-table-column v-if="isPc" prop="brand" label="品牌"></el-table-column>
                <el-table-column prop="name" label="商品名"></el-table-column>
                <el-table-column label="规格">
                    <template slot-scope="scope">
                        {{scope.row.uniq_attr}}
                    </template>
                </el-table-column>
                <el-table-column label="售价">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row[field]" size="small"></el-input>
                    </template>
                </el-table-column>
                <el-table-column width="155px" label="数量">
                    <template slot-scope="scope">
                        <el-input-number size="small" v-model="scope.row.num"></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column prop="balance" label="金额"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button
                                type="text"
                                icon="el-icon-delete"
                                @click="handleDel(scope.$index)"
                        >删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 确认金额 -->
        <el-dialog title="确认提交" :visible.sync="submitVisible"  :width="modalWidth" :close-on-click-modal="false">
            <el-form ref="form" id="add-dialog" style="padding: 0" label-width="80px">
                <el-form-item label="付款方式">
                  <el-select   v-model="payType" clearable placeholder="选择付款类型" class="handle-select" @change="setDeductMoney" style="width: 100%">
                    <el-option  key="0" label="现结" value="0" ></el-option>
                    <el-option  key="1" label="赊账" value="1" ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="实收金额">
                    <el-input v-model="realBalance" id="real-balance-input"  class="add-dialog-input"
                    ></el-input>
                </el-form-item>
                <el-form-item label="扣除余额">
                    <el-input v-model="deductMoney"  class="add-dialog-input"></el-input>
                </el-form-item>
                <el-form-item label="还需付款">
                    <span style="margin-left: 15px">{{needPay}}</span>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="submitVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveOrder">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 新增用户 -->
        <el-dialog title="新增用户" :visible.sync="addUserVisible"  :width="modalWidth" :close-on-click-modal="false">
            <el-form ref="form" style="padding: 0" label-width="80px">
                <el-form-item label="电话">
                    <el-input v-model="addForm.mobile"  class="add-dialog-input" ></el-input>
                </el-form-item>
                <el-form-item label="姓名">
                    <el-input v-model="addForm.nickname"  placeholder="" class="add-dialog-input" ></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addUserVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveUser">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: 'goods',
        data() {
            return {
                bar_code: '',
                tableData: [],
                submitVisible: false,
                addUserVisible: false,
                modalWidth: '70%',
                realBalance: 0,
                pageIndex: 1,
                pageSize: 20,
                addForm: {
                    mobile: '',
                    nickname: '',
                },
                qryStr: '',
                userId: 0,
                field: 'sell_price',
                couponArr: [],
                couponId: 0,
                couponPrice: 0,
                couponTitle: '',
                userMoney: 0,
                deductMoney:0,
                payType: "0",
                isPc: false
            };
        },
        activated: function () {
            document.getElementById("bar-code-input").focus();
        },
        created() {
            if (document.body.clientWidth > 768) {
                this.modalWidth = '30%'
                this.isPc = true
            }
            this.http.curUser().then(res => {

            }).catch(err => {
                this.$message.error("登录过期,请重新登录");
                this.$router.push("/login")
            })
        },
        // directives: {
        //     focus:function (el) {
        //         el.querySelector("#bar-code-input").focus();
        //     }
        // },
        directives: {
            focus: {
                inserted: function(el) {
                    el.querySelector("#bar-code-input").focus();
                }
            }
        },
        methods: {
            getSummaries(param) {
                const { columns, data } = param;
                const sums = [];
                columns.forEach((column, index) => {
                    if (index === 0) {
                        sums[index] = '总额';
                        return;
                    }
                    if(column.property === 'balance') {
                        const values = data.map(item => Number(item['balance']));
                        let totalAmount = values.reduce((prev, curr) => {
                            const value = Number(curr);
                            if (!isNaN(value)) {
                                return prev + curr;
                            } else {
                                return prev;
                            }
                        }, 0);
                        sums[index] = '总价 ' + (totalAmount - this.couponPrice)
                    }
                });
                return sums;
            },
            handleDel(idx){
                this.tableData.splice(idx, 1)
            },
            saveUser() {
              this.http.addUser(this.addForm).then(res => {
                console.log(res)
                if(res.code === 0) {
                  this.$message.success("新增成功");
                  this.addUserVisible = false
                } else {
                  this.$message.error(res.msg);
                }
              })
            },
            confirmCoupon(id){
                this.couponId = 0
                this.couponPrice = 0
                this.couponArr.forEach(item => {
                    if(item.id === id) {
                        this.couponId = id
                        this.couponPrice = item.price
                        this.couponTitle = item.title
                    }
                })
            },
            openDialog(){
                let totalBalance = 0;
                for (let  i = 0; i < this.tableData.length; i++) {
                    totalBalance += Math.floor(this.tableData[i].num * this.tableData[i][this.field] * 100) / 100
                }
                this.submitVisible = true;
                this.realBalance = parseFloat(totalBalance - this.couponPrice).toFixed(1)
                this.setDeductMoney()
            },
            isBarCode(name) {
                const pattern = /^\d{11}\d+$/;
                return pattern.test(name)
            },
            setDeductMoney() {
                if (this.payType === '1') {
                  this.deductMoney = this.realBalance
                } else {
                  this.deductMoney = parseInt(this.userMoney * 100) > parseInt(this.realBalance * 100) ?
                      this.realBalance : this.userMoney
                }
            },
            saveOrder () {
                let postArr = [];
                let totalBalance = 0;
                for (let  i = 0; i < this.tableData.length; i++) {
                    totalBalance += Math.floor(this.tableData[i].num * this.tableData[i][this.field] * 100) / 100;
                    let _ = {};
                    _.sku_id = this.tableData[i].id  + '';
                    _.num = this.tableData[i].num + '';
                    _.price = this.tableData[i][this.field] + '';
                    postArr.push(_)
                }
                if (totalBalance === 0) {
                  this.$message.error("结账金额为0，请先选择结账商品")
                  this.submitVisible = false
                  return false
                }
                if (this.payType === '1' && this.userId === 0) {
                  this.$message.error("请先选择赊账人员")
                  return false
                }
                this.http.addOrder({data: JSON.stringify(postArr),
                    total: this.realBalance,
                    couponId: this.couponId,
                    pay_type: this.payType,
                    deduct_money: parseInt(this.deductMoney * 100),
                    user_id: this.userId}).then(res => {
                    if(res.code === 0) {
                        this.$message.success("结账完成");
                        this.tableData = []
                    }
                });
                this.submitVisible = false
                this.clearSelect()
            },

            payCode() {
                this.http.getSku(this.bar_code).then(res => {
                    if(res.data.bar_code === undefined) {
                        this.$message.error("商品条形码不存在,请先录入该条形码");
                        this.bar_code = '';
                        return false
                    }
                    this.addToList(res.data)
                })
            },
            addToList(resData){
                for (let i =0; i < this.tableData.length; i++ ) {
                    if(this.tableData[i].bar_code === resData.bar_code) {
                        this.tableData[i].num += 1;
                        this.bar_code = '';
                        return true
                    }
                }
                resData.num = 1;
                this.tableData.unshift(resData);
                this.bar_code = '';
                return true
            },
            querySearchSkus(queryString, cb) {
                if(this.isBarCode(queryString)) {
                    this.payCode();
                    cb([])
                } else {
                    this.http.getSkuList({name: queryString, pageSize: 50}).then(res => {
                        let result = res.data.list ? res.data.list : [];
                        result.forEach(item => {
                            item.value = item.name + ' ' + item.uniq_attr + '    ¥' + item.sell_price
                        });
                        cb(result)
                    });
                }
            },
            handleSelect(item) {
                this.addToList(JSON.parse(JSON.stringify(item)))
            },
            queryUserName(queryString, cb){
                this.http.getUsers({mobile: this.qryStr, with_coupon: 1}).then(res => {
                    let ret = [];
                    const users = res.data.list;
                    const coupon = res.data.coupon_list;
                    if (users instanceof Array) {
                        users.forEach(item => {
                            let _ = {};
                            _.value = item.mobile + (item.nickname ? ' ' + item.nickname : '');
                            _.id = item.id;
                            _.money = item.money;
                            _.level_txt = item.level_txt;
                            _.coupon = coupon[item.id] ? coupon[item.id] : [];
                            ret.push(_)
                        })
                    }
                    cb(ret);
                });
            },
            confirmSelect(item){
                this.userId = parseInt(item.id);
                this.userMoney = parseFloat(item.money).toFixed(1);
                this.couponArr = item.coupon
            },
            clearSelect(){
                this.userId = 0;
                this.userMoney = 0;
                this.couponArr = [];
                this.qryStr = ''
            },
        },
        computed: {
            computedTableData: function () {
                for (let i = 0; i < this.tableData.length; i++) {
                    this.tableData[i].balance = Math.floor(this.tableData[i][this.field] * this.tableData[i].num * 100) / 100
                }
                this.tableData.push({});
                this.tableData.pop();
                return this.tableData;
            },
            needPay: function () {
                return (this.realBalance - this.deductMoney).toFixed(1)
            }
        },

    };
</script>

<style scoped>


    .table {
        width: 100%;
        font-size: 14px;
    }
    .red {
        color: #ff0000;
    }
    .mr10 {
        margin-right: 10px;
    }
    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }
    .el-button--mini.is-circle{
        padding: 2px;
    }
</style>
